package no.hib.quiz;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

public class MainActivity extends FragmentActivity {
	
	public static List<Quiz> quizList;
	public static int quizNumber;
	public static SharedPreferences prefs;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_layout);
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String quiz_list_json = prefs.getString("quiz_list", null);
		if (quiz_list_json != null) {
			Type type = new TypeToken<List<Quiz>>(){}.getType();
		    quizList = new Gson().fromJson(quiz_list_json, type);
		}
		else {
			quizList = new ArrayList<Quiz>();
		}
		
	    if (findViewById(R.id.fragment_container) != null) {

	        if (savedInstanceState != null) {
	            return;
	        }
	 
	        MenuFragment menu = new MenuFragment();
	        
	        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, menu).commit();
	    }
	}
	
	@Override
	public void onPause() {
	    super.onPause();  
	    
	    String json = new Gson().toJson(quizList);
	    prefs.edit().putString("quiz_list", json);

	    
	}
		
		
		

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
